<template>
  <div class="page-main" v-title :data-title="dataTitle ? dataTitle : '验收付款单'">
    <a-spin :spinning="spinning" :tip="spinTip" v-on:dblclick="spinning=false">
    <FixedMenu />
    <home-nav :userData="userinfo"></home-nav>
    <div class="container" ref="imageWrapper">
      <a-alert
        :message="alertMsg"
        :description="alertDesc"
        type="success"
        show-icon
        v-if="alertShow"
        @close="alertShow = true"
        close-text="X"
      >
      </a-alert>
      <div class="head-content">
        <span class="bold-font">合同验收付款审批表</span>
        <ul>
          <li @click="toTaskDetail">
            <a-icon type="file-search" />
            报工单详情
          </li>
          <li @click="toContractAttach">
            <a-icon type="link" />
            合同附件
          </li>
          <li @click="openSettlementDetail">
            <a-icon type="link" />
            核算表
          </li>
          <li @click="toTaskList">
            <a-icon type="link" />
            报工任务单
          </li>
        </ul>
        <div class="btn-line">
          <a-button class="hte-btn" v-if="taskCheckBtnShow" @click="(event)=>reportTaskCheck()">异常检测</a-button>
          <a-button
            v-if="checkPermission(['WORK_REPORT_ADMIN'])"
            class="hte-btn add-btn"
            type="primary"
            @click="updateStatus"
            >更新审批状态</a-button
          >
          <a-button class="hte-btn add-btn" type="primary" @click="print">付款打印</a-button>
          <a-button class="hte-btn add-btn" type="primary" @click="print1">验收打印</a-button>
          <!-- <a-button class="hte-btn add-btn" type="primary" @click="printSnap">打印快照</a-button> -->
          <a-button class="hte-btn add-btn" type="primary" @click="handleSave">保存</a-button>
          <a-button
            v-if="
              (task.currentHandlerUser == '1' || checkPermission(['WORK_REPORT_MANAGER', 'WORK_REPORT_ACCEPTER'])) &&
              (!payment.status || payment.status == '0' || payment.status == '3')
            "
            class="hte-btn"
            @click="handleSubmit"
            >提交审批</a-button
          >
          <a-button
            v-if="process.taskDefKey == 'POST_DEPT_NODE' || checkPermission(['WORK_REPORT_MANAGER'])"
            class="hte-btn"
            @click="handleReAutoPost"
            >重新过账</a-button
          >
        </div>
      </div>

      <div>
        <div ref="printSnapContainer" id="printSnapContainer" style="width: 690px">
          <image
            v-if="payment.processInstanceId"
            width="650px"
            :src="hteBootApi + '/ps/workReport/downloadLastestSnap?processInstanceId=' + payment.processInstanceId"
          />
        </div>
      </div>
      <div class="content">
        <a-form-model ref="ruleForm" :model="payment" :rules="rules">
          <section>
            <div class="section-header">{{ payment.isSendPay != 1 ? '合同基本' : '付款申请' }}信息</div>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="申请流水号">
                  <a-input v-model="payment.applyNo" disabled placeholder="自动带入" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请人">
                  <a-input v-model="payment.applyUserName" disabled placeholder="自动带入" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请时间">
                  <a-date-picker disabled valueFormat="YYYY-MM-DD" v-model="payment.applyTime" placeholder="自动带入" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="合同编号">
                  <a-input disabled v-model="project.contractNumber" placeholder="自动带入" />
                </a-form-model-item>
              </a-col>
              <a-col :span="16">
                <a-form-model-item label="合同名称">
                  <a-input disabled v-model="project.contractName" placeholder="自动带入" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="合同总金额">
                  <a-input disabled v-model="project.amount" placeholder="自动带入" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="签订公司">
                  <a-input
                    disabled
                    :value="project.signCompany + '/' + project.signCompanyCode"
                    placeholder="自动带入"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="供应商名称">
                  <a-input disabled v-model="project.supplierName" placeholder="自动带入" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="采购订单号">
                  <a-input disabled v-model="project.busKey" placeholder="自动带入" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="费用支出号">
                  <a-input disabled placeholder="自动带入" v-model="task.costNumber" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="合同签订主管">
                  <UserInputSelector
                    :username.sync="project.deptHeadId"
                    :realname.sync="project.deptHead"
                    :disabled="!checkPermission(['WORK_REPORT_ADMIN', 'WORK_REPORT_MANAGER'])"
                    multiple="default"
                    placeholder="请选择"
                  />
                  <!-- <a-input
              :disabled="!checkPermission(['WORK_REPORT_ADMIN', 'WORK_REPORT_MANAGER'])"
              v-model="project.projectCode"
            /> -->
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="项目经理" prop="proManager">
                  <UserInputSelector
                    :username.sync="payment.proManagerId"
                    :realname.sync="payment.proManager"
                    :disabled="payment.status == '2'"
                    multiple="default"
                    placeholder="请选择"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="合同签订人">
                  <a-input disabled v-model="project.signUser" placeholder="自动带入" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="合同跟进专员">
                  <a-input disabled v-model="project.createOrderUser" placeholder="自动带入" />
                </a-form-model-item>
              </a-col>
            </a-row>
          </section>
          <section>
            <div class="section-header">节点完成情况</div>
            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-model-item label="工期节点内容">
                  <a-input v-model="task.nodeContent" disabled placeholder="自动带入" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-model-item label="付款节点内容">
                  <a-input v-model="task.paymentContent" disabled placeholder="自动带入" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="项目负责人">
                  <a-input disabled v-model="task.handlerUser" placeholder="自动带入" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="付款节点标志">
                  <a-input disabled :value="task.isPayNode == '1' ? '是' : '否'" placeholder="自动带入" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="合同节点标志">
                  <a-input disabled v-model="task.nodeIdentify" placeholder="自动带入" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item class="col-input-2 col-input-font" label="工期节点进度">
                  <a-select disabled v-model="task.partaNodeStatus">
                    <a-select-option
                      v-for="(item, index) in codes.WorkReportResultStatus"
                      :key="'nodeStatus' + index"
                      :value="item.code"
                    >
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                  <a-input
                    v-if="task.partaNodeStatus == '逾期'"
                    disabled
                    v-model="task.partaDelayDays"
                    placeholder="自动带入"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item ref="delayReason" label="逾期责任方">
                  <a-select disabled v-model="task.partaDelayReason">
                    <a-select-option
                      v-for="(item, index) in codes.WorkReportDelayReson"
                      :key="'delayReason' + index"
                      :value="item.code"
                    >
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                  <a-input
                    disabled
                    v-if="task.partaDelayReason == '双方'"
                    v-model="task.partaDelayDays"
                    placeholder="自动带入"
                    addonBefore="甲方逾期"
                    suffix="天"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="工期节点质量">
                  <a-select disabled v-model="task.partaResult">
                    <a-select-option
                      v-for="(item, index) in codes.WorkReportResultType"
                      :key="'result' + index"
                      :value="item.code"
                    >
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="凭保证函付款" prop="payByLetter">
                  <CodeSelector
                    type="radio"
                    :codes="codes['是否']"
                    codeKey="name"
                    nameKey="name"
                    :code.sync="payment.payByLetter"
                    multiple="default"
                    :disabled="
                      process.taskDefKey != 'APPLY_USER_NODE'  && payment.status && payment.status != 0 && payment.status != 3
                    "
                  ></CodeSelector>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="合同资料情况" prop="fileCondition">
                  <a-select
                    :disabled="
                      process.taskDefKey != 'APPLY_USER_NODE' &&  payment.status && payment.status != 0 && payment.status != 3
                    "
                    v-model="payment.fileCondition"
                  >
                    <a-select-option
                      v-for="(item, index) in codes.FileCondition"
                      :key="'fileCondition' + index"
                      :value="item.code"
                    >
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="项目所在地" :prop="task.nodeIdentify != '验收' ? '' : 'projectAddr'">
                  <a-input
                    :disabled="
                      process.taskDefKey != 'APPLY_USER_NODE' &&  payment.status && payment.status != 0 && payment.status != 3
                    "
                    v-model="payment.projectAddr"
                    placeholder="填写所在城市地名"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="验收参与部门" :prop="task.nodeIdentify != '验收' ? '' : 'acceptDept'">
                  <a-input
                    :disabled="
                      process.taskDefKey != 'APPLY_USER_NODE' &&  payment.status && payment.status != 0 && payment.status != 3
                    "
                    v-model="payment.acceptDept"
                    placeholder="填写验收参与部门"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="验收参与人" :prop="task.nodeIdentify != '验收' ? '' : 'acceptUserName'">
                  <a-input
                    :disabled="
                      process.taskDefKey != 'APPLY_USER_NODE' &&  payment.status && payment.status != 0 && payment.status != 3
                    "
                    v-model="payment.acceptUserName"
                    placeholder="填写验收参与人"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="设备所在位置" :prop="task.nodeIdentify != '验收' ? '' : 'equipmentAddr'">
                  <a-input
                    :disabled="
                      process.taskDefKey != 'APPLY_USER_NODE' &&  payment.status && payment.status != 0 && payment.status != 3
                    "
                    v-model="payment.equipmentAddr"
                    placeholder="填写设备设施位置，没有则填'无'"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item
                  label="使用部门成本中心"
                  :prop="process.taskDefKey == 'useDept'  ? 'costNumber' : ''"
                >
                  <a-input
                    :disabled="process.taskDefKey != 'APPLY_USER_NODE' && process.taskDefKey == 'useDept'"
                    v-model="payment.costNumber"
                    placeholder="使用部门填写"
                    readOnly
                    @click="selectCostCenter"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="质保期限" :prop="task.nodeIdentify != '验收' ? '' : 'warrantyYears'">
                  <a-input
                    :disabled="
                      process.taskDefKey != 'APPLY_USER_NODE' && payment.status && payment.status != 0 && payment.status != 3
                    "
                    v-model="payment.warrantyYears"
                    style="width: 100%"
                    placeholder="合同中约定的质保期，如24个月(请填写整数月数)"
                    type="number"
                    suffix="个月"
                    @change="changeWarrantyYears"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="质保到期日">
                  <a-date-picker
                    :disabled="
                      process.taskDefKey != 'APPLY_USER_NODE' &&
                      payment.status &&
                      payment.status != 0 &&
                      payment.status != 3 &&
                      process.taskDefKey != 'FOLLOW_USER_NODE'
                    "
                    style="width: 100%"
                    valueFormat="YYYY-MM-DD"
                    placeholder="合同跟进人填写"
                    v-model="payment.warrantyTime"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-model-item label="验收补充说明">
                  <a-textarea
                    :auto-size="{ minRows: 2, maxRows: 6 }"
                    :maxLength="500"
                    :disabled="
                      process.taskDefKey != 'APPLY_USER_NODE' && payment.status && payment.status != 0 && payment.status != 3
                    "
                    v-model="payment.taskRemmark"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
          </section>
          <section v-if="!process.taskDefKey || (process.taskDefKey != 'userDept' && process.taskDefKey != 'keepDept')">
            <div class="section-header">
              <div>合同付款信息<a-button  style="font-size: 12px; font-weight: normal" v-if="project.id" type="link" @click="openTaskPop">付款节点列表</a-button></div>
              <span style="font-size: 12px; color: red; padding-left: 20px; font-weight: normal"
                >由合同跟进专员根据质量通知单审批更新付款信息</span
              >
            </div>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item class="col-input-2" label="PO单行号">
                  <a-input v-model="task.poLine" disabled />
                  <a-input v-model="project.poLineCountCopy" disabled />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="节点金额(含税)">
                  <a-input disabled v-model="task.paymentAmount" placeholder="单位：元" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="水电费承担方">
                  <div class="disabled-radio">
                    <CodeSelector
                      type="radio"
                      :codes="codes['甲方乙方']"
                      codeKey="code"
                      nameKey="name"
                      :code.sync="project.waterAndElectricityPay"
                      disabled
                      multiple="default"
                    ></CodeSelector>
                  </div>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="税率">
                  <a-input disabled v-model="task.taxRate" placeholder="自动带入" suffix="%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="本次支付金额(含税)">
                  <a-input
                    v-if="
                    (payment.status=='1' && ['APPLY_USER_NODE','FOLLOW_USER_NODE','PURCHASE_DEPT_USER'].indexOf(process.taskDefKey)>-1)
                    ||
                    userinfo.info.username == 'liangyq5' 
                    || (['0','3'].indexOf(payment.status)>-1  && payment.isPrePay=='是')
                    "
                    v-model="payment.payAmount"
                    placeholder="单位：元，自动计算，可修改"
                  />
                  <a-input
                    v-else
                    disabled
                    v-model="payment.payAmount"
                    placeholder="单位：元，自动计算，可修改"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="本次过账金额(含税)">
                  <a-input
                    v-if="
                    (payment.status=='1' && ['APPLY_USER_NODE','FOLLOW_USER_NODE','PURCHASE_DEPT_USER'].indexOf(process.taskDefKey)>-1)
                    ||
                    userinfo.info.username == 'liangyq5' 
                    || (['0','3'].indexOf(payment.status)>-1  && payment.isPrePay=='是')
                    "
                    v-model="payment.postAmount"
                    placeholder="单位：元，自动计算，可修改"
                  />
                  <a-input
                    v-else
                    disabled
                    v-model="payment.postAmount"
                    placeholder="单位：元，自动计算，可修改"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>

            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="是否预付">
                  <CodeSelector
                    type="select"
                    :codes="codes['是否']"
                    codeKey="name"
                    nameKey="name"
                    :code.sync="payment.isPrePay"
                    multiple="default"
                    :disabled="!checkPermission(['WORK_REPORT_MANAGER'])"
                  ></CodeSelector>
                </a-form-model-item>
              </a-col>
              <a-col :span="16">
                <a-form-model-item label="付款补充说明">
                  <a-input
                    v-if="
                    (payment.status=='1' && ['APPLY_USER_NODE','FOLLOW_USER_NODE','PURCHASE_DEPT_USER'].indexOf(process.taskDefKey)>-1)
                    ||
                    userinfo.info.username == 'liangyq5' 
                    || (['0','3'].indexOf(payment.status)>-1  && payment.isPrePay=='是')
                    "
                    v-model="payment.remark"
                    placeholder="填写补充说明信息"
                  />
                  <a-input
                    v-else
                    disabled
                    v-model="payment.remark"
                    placeholder="填写补充说明信息"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="是否数字贷：">
                  <CodeSelector
                    type="radio"
                    :codes="yesOrNot"
                    codeKey="code"
                    nameKey="name"
                    :code.sync="payment.digitalLoan"
                    multiple="default"
                    @change="changeDiaitalLoan"
                  ></CodeSelector>
                </a-form-model-item>
              </a-col>
              <a-col :span="16">
                <a-form-model-item label="备案证名称：" :prop="payment.digitalLoan ? 'digitalLoan' : ''">
                  <a-select v-model="payment.filingName" allowClear :disabled="!payment.digitalLoan">
                    <a-select-option
                      v-for="(item, index) in codes['数字贷备案证名称']"
                      :key="'filingName' + index"
                      :value="item.name"
                    >
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
            </a-row>
            <div class="line-section">
              <div>
                <span>质量通知单累计扣罚金额:</span>
                <span
                  >扣罚金额合计（元）：<i>{{ payment.fineAmount }}</i></span
                >
                <span
                  >减少开票金额（元）：<i>{{ payment.reduceAmount }}</i></span
                >
                
                  <span>
                  <a-button type="link" @click="toQualityListByPo">质量通知单列表</a-button>
                  </span> 
                
                <span>
                  <a-button type="link" @click="relateQualityListByPo">相关质量通知单</a-button>
                </span>
              </div>
              <div>
                <a-button type="link" @click="reloadQualityList">加载最新质量通知单</a-button>
              </div>
            </div>
            <a-table
              class="hte-table-content"
              :columns="columns"
              :data-source="qualityRecords"
              rowKey="id"
              bordered
              size="middle"
              :pagination="false"
              @change="handleTableChange"
            >
              <span slot="qualityTypeRender" slot-scope="text, record">
                <CodeSelector
                  type="select"
                  :codes="codes['质量通知单类型']"
                  codeKey="code"
                  nameKey="name"
                  :code.sync="record.qualityType"
                  disabled
                  multiple="multiple"
                ></CodeSelector>
              </span>
              <span slot="qualityNoRender" slot-scope="text, record">
                <span class="font-active" @click="toQuality(record)">{{ record.qualityNo }}</span>
              </span>
              <span slot="oaLshRender" slot-scope="text, record">
                <span class="font-active" @click="toQuality(record)">{{ text }}</span>
              </span>
              <span slot="reduceRender" slot-scope="text, record, index">
                <CodeSelector
                  type="select"
                  :codes="codes['减少不变']"
                  codeKey="code"
                  nameKey="name"
                  :code.sync="qualityRecords[index].reduce"
                  v-if="
                    (payment.status=='1' && ['APPLY_USER_NODE','FOLLOW_USER_NODE','PURCHASE_DEPT_USER'].indexOf(process.taskDefKey)>-1)
                    ||
                    userinfo.info.username == 'liangyq5' 
                    || (['0','3'].indexOf(payment.status)>-1  && payment.isPrePay=='是')
                    "
                  @change="toCalcReduce(index, 'reduce')"
                  multiple="default"
                ></CodeSelector>
                <CodeSelector
                  v-else
                  type="select"
                  :codes="codes['减少不变']"
                  codeKey="code"
                  nameKey="name"
                  :code.sync="qualityRecords[index].reduce"
                  disabled
                  @change="toCalcReduce(index, 'reduce')"
                  multiple="default"
                ></CodeSelector>
              </span>
              <span slot="fineRender" slot-scope="text, record, index">
                <CodeSelector
                  type="select"
                  :codes="codes['是否']"
                  codeKey="code"
                  nameKey="name"
                  :code.sync="qualityRecords[index].fine"
                  v-if="
                    (payment.status=='1' && ['APPLY_USER_NODE','FOLLOW_USER_NODE','PURCHASE_DEPT_USER'].indexOf(process.taskDefKey)>-1)
                    ||
                    userinfo.info.username == 'liangyq5' 
                    || (['0','3'].indexOf(payment.status)>-1  && payment.isPrePay=='是')
                    "
                  @change="toCalcReduce(index, 'fine')"
                  multiple="default"
                ></CodeSelector>
                <CodeSelector
                  v-else
                  disabled
                  type="select"
                  :codes="codes['是否']"
                  codeKey="code"
                  nameKey="name"
                  :code.sync="qualityRecords[index].fine"
                  @change="toCalcReduce(index, 'fine')"
                  multiple="default"
                ></CodeSelector>
              </span>
              <template slot="statusRender" slot-scope="text, record">
                <a-select disabled :value="record.status + ''" style="width: 100%">
                  <a-select-option
                    v-for="(code, index) in codes.WorkReportQualityStatus"
                    :key="index"
                    :value="code.code"
                  >
                    {{ code.name }}
                  </a-select-option>
                </a-select>
              </template>
              <template slot="activeRender" slot-scope="text, record">
                <a-button
                  v-if="
                    process.taskDefKey != 'APPLY_USER_NODE' && 
                    process.taskDefKey == 'FOLLOW_USER_NODE' ||
                    process.taskDefKey == 'PURCHASE_DEPT_USER' ||
                    checkPermission(['WORK_REPORT_MANAGER', 'WORK_REPORT_ACCEPTER'])
                  "
                  type="link"
                  @click="removePaymentQuality(record)"
                  >移除</a-button
                >
              </template>
            </a-table>
          </section>
        </a-form-model>
        <section v-if="payment.id">
          <div class="section-header">附件列表</div>
          <PaymentWorkAttachList
            busType="ITEM_PAYMENT"
            :busKey="payment.id + ''"
            :taskId="task.id"
            :permission="permission"
            :payment="payment"
            :project="project"
          />
        </section>
        <section v-if="payment.processInstanceId" class="approvalBox">
          <div class="section-header">审批记录</div>
          <div>
            <div style="display: flex; margin-bottom: 10px">
              <a-button class="hte-btn add-btn" type="primary" @click="showPaymentFlowTips = true"
                >审批流程指引</a-button
              >
            </div>
            <ht-approval
              :key="payment.processInstanceId"
              ref="childrenRef"
              :process-instance-id="payment.processInstanceId"
              :custom="custom"
              :options="options"
              @submit="afterSubmit"
              @reject="afterReject"
              @back="backAction"
              @cancelSubmit="afterCancelSubmit"
              :before-fill-opinion="saveNotifyOpinion"
              :before-submit="beforeSubmit"
              :before-reject="beforeReject"
              :show-task-history="true"
              :history-dialog="historyDialog"
              :task-load="taskLoad"
              :message-id="messageId"
              :showPrintBtn="showPrintBtn"
              :show-upload-btn="false"
              :hidden-task-def-key="hiddenTaskDefKey"
              :snapshotConfigs="snapshotConfigs"
              :print="print"
            >
            </ht-approval>
            <a-modal
              title="审批流程指引"
              :visible="showPaymentFlowTips"
              @ok="showPaymentFlowTips = false"
              @cancel="showPaymentFlowTips = false"
              width="80vw"
              :maskClosable="false"
            >
              <img src="~@assets/payment_flow_tips.png" />
            </a-modal>
          </div>
        </section>
      </div>
    </div>


    <!-- 相关质量通知单 -->
  <RelateQualityListByPo 
    :show="showRelateQualityListByPo" 
    :orderNo="project.busKey" 
    :supplierCode="project.supplierCode"
    @close="closeRelateQuanlityListByPo">
  </RelateQualityListByPo>

    <!-- <DeptSelector :show="showDeptSelector" @selected="selectDept" /> -->
    <UserSelector :show="showUserSelector" :deptCode="deptCode" :muti="muti" @selected="selectUser" />
    <ProcessUserSelect ref="ProcessUserSelect" @selectUserConfirm="selectUserConfirm" />
    <!-- 付款打印页面排版 -->

    <div style="visibility: hidden; position: fixed">
      <printPayment
        ref="printPayment"
        :project="project"
        :task="task"
        :payment="payment"
        :qualityRecords="qualityRecords"
        :comments="comments"
        :notifys="notifys"
      />
    </div>
    <!-- 验收打印页面排版 -->

    <div style="visibility: hidden; position: fixed">
      <printAccept
        ref="printAccept"
        :project="project"
        :task="task"
        :payment="payment"
        :codes="codes"
        :comments="comments"
      />
    </div>
    <SettlementDetail
      :show="showSettlementDetail"
      :supplierCode="project.supplierCode"
      :wbs="task.costNumber"
      :taskInfoId="task.id"
      @close="closeSettlementDetail"
      :edit="false"
    />
    <!--成本中心号选择-->
    <table-select-modal
      ref="costCenterSelect"
      :title="costCenterData.title"
      :searchPlaceholder="costCenterData.searchPlaceholder"
      :importColumns="costCenterData.columns"
      :params="costCenterData.params"
      :keywordKey="costCenterData.keywordKey"
      :isAllSelect="false"
      :listUrl="costCenterData.url"
      @ok="costCenterHandleOk"
    />
    <TaskPop ref="TaskPop"/>
  </a-spin>
    <a-modal title="检测结果" :visible="taskCheckShow" @ok="taskCheckOk" @cancel="taskCheckShow=false" width="800px" :maskClosable="false" :okText="taskCheckOkText">
      <div>
        <a-form-model ref="checkForm">
          <a-row :gutter="24">
            <a-col :span="5">
              <div style="line-height:40px;width:100%;text-align: right;font-weight: bolder;font-size:15px;color: #0b88d8"><span>检测对象：</span></div>
            </a-col>
            <a-col :span="8">
              <a-form-model-item label="采购单号:"  style="font-weight: bolder;font-size:15px;">
                <span>{{project.busKey}}</span>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item label="订单行号："  style="font-weight: bolder;font-size:15px;">
                <span>{{task.poLine}}</span>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="24">
              <div style="line-height: 20px;"><span>1、费用支出号检测：</span></div>
              <a-textarea
                :style="{'border-color': taskCheckResult.checkCostNumberResult.checkResult=='0'?'red':'#d9d9d9','width':'100%'}"
                readOnly
                :auto-size="{ minRows: 2, maxRows: 6 }"
                v-model="taskCheckResult.checkCostNumberResult.checkMsg"
              />
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="24">
              <div style="line-height: 20px;"><span>2、合同节点金额检测：</span></div>
              <a-textarea
                :style="{'border-color': taskCheckResult.checkAmountResult.checkResult=='0'?'red':'#d9d9d9'}"
                readOnly
                :auto-size="{ minRows: 2, maxRows: 6 }"
                v-model="taskCheckResult.checkAmountResult.checkMsg"
              />
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="24">
              <div style="line-height: 20px;"><span>3、在途补充协议检测：</span></div>
              <a-textarea
                :style="{'border-color': taskCheckResult.checkAuditingResult.checkResult=='0'?'red':'#d9d9d9'}"
                readOnly
                :auto-size="{ minRows: 2, maxRows: 6 }"
                v-model="taskCheckResult.checkAuditingResult.checkMsg"
              />
            </a-col>
          </a-row>
        </a-form-model>
      </div>
    </a-modal>
  </div>
</template>

<script>
import { getAction, postAction, getActionAsync } from '@/api/manage'
import { formatDate, calcDaysBetween } from '@/utils/util'
import { FlowMixin } from '@/mixins/FlowMixin'
import { CodesMixin } from '@/mixins/CodesMixin'
import { Modal } from 'ant-design-vue'
export default {
  inject: ['reload'],
  props: {
    taskId: {
      type: String,
      default: null,
    },
  },
  mixins: [FlowMixin, CodesMixin],
  components: {
    HomeNav: () => import('@/components/layouts/HomeNav'),
    htApproval: () => import('@/config/ht-approval.umd.min.js'),
    PaymentWorkAttachList: () => import('@/views/workReport/attach/PaymentWorkAttachList'),
    UserSelector: () => import('@/views/workReport/role/UserSelector'),
    ProcessUserSelect: () => import('@/components/tools/ProcessUserSelect'),
    SettlementDetail: () => import('@/views/workReport/util/SettlementDetail'),
    printPayment: () => import('@/views/workReport/payment/printPayment'),
    printAccept: () => import('@/views/workReport/payment/printAccept'),
    TaskPop: () => import('@/views/workReport/payment/TaskPop'),
    TableSelectModal: () => import('@/components/tools/TableSelectModal'),
    FixedMenu: () => import('@/views/workReport/home/FixedMenu'),
    RelateQualityListByPo: () => import('@/views/workReport/payment/relateQualityListByPo'),
  },
  data() {
    return {
      dataTitle: this.$route ? this.$route.name : '',
      hteBootApi: process.env.VUE_APP_API_BASE_URL,
      paymentId: this.$route.params && this.$route.params.paymentId,
      userinfo: {
        info: this.$store.getters.userInfo,
        module: 'ContractReportInfo',
      },
      rules: {
        payByLetter: [{ required: true, message: '请选择', trigger: 'blur' }],
        fileCondition: [{ required: true, message: '请选择', trigger: 'blur' }],
        projectAddr: [{ required: true, message: '请输入', trigger: 'blur' }],
        acceptDept: [{ required: true, message: '请输入', trigger: 'blur' }],
        acceptUserName: [{ required: true, message: '请输入', trigger: 'blur' }],
        equipmentAddr: [{ required: true, message: '请输入', trigger: 'blur' }],
        warrantyYears: [{ required: true, message: '请输入', trigger: 'blur' }],
        costNumber: [{ required: true, message: '请输入', trigger: 'blur' }],
        proManager: [{ required: true, message: '请选择', trigger: 'blur' }],
        digitalLoan: [{ required: true, message: '请选择', trigger: 'blur' }],
      },
      payment: { payByLetter: '否' },
      urls: {
        payment: '/workReport/payment/info',
        editPayment: '/workReport/payment/edit',
        task: '/workReport/task/info',
        taskCheck: '/workReport/task/check',
        project: '/workReport/project/info',
        psQualityList: '/hte/contract/qualityList',
        hteQualityList: '/workReport/quality/list',
        myPermission: '/workReport/project/myPermission',
        codes: '/manage/codeInfo/queryByTypes',
        getProcessComment: '/workReport/payment/getProcessComment',
        checkDuplicatePayment: '/workReport/payment/checkDuplicatePayment',
        reAutoPost: '/workReport/payment/reAutoPost',
        loadSignCompany: '/hte/contract/loadSignCompany',
        getProcessMap: '/workReport/payment/getProcessMap',
        checkProjectBUildDigitalLoan: '/projectBuild/getProjectByNo',
        paymentQualityList: '/paymentQuality/list',
        reloadQualityList: '/workReport/payment/reloadQualityList',
        removePaymentQuality: '/paymentQuality/delete',
        flowNode: '/workReport/payment/flowNode',
        startFlow: '/workReport/payment/startFlow',
        relateQualityToTaskPayment:'/workReport/payment/relatedQualityToTaskPayment'
      },
      approvalActions: {
        passUrl: '/workReport/payment/updateStatus',
        rejectUrl: '/workReport/payment/updateStatus',
        changeHasPost: '/workReport/payment/changeHasPost',
      },
      labelCol: {
        span: 8,
      },
      wrapperCol: {
        span: 15,
      },
      task: {
        currentHandlerUser: '',
      },
      project: {
        waterAndElectricityPay: '1',
      },
      showDeptSelector: false,
      showUserSelector: false,
      deptCode: '-1',
      userSelectType: 'apply',
      qualityQuery: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        total: 0,
      },

      columns: [
        {
          title: '质量通知单',
          dataIndex: 'qualityNo',
          width: '140px',
          align: 'center',
          scopedSlots: {
            customRender: 'qualityNoRender',
          },
        },
        {
          title: 'OA流水号',
          dataIndex: 'oaLsh',
          width: '140px',
          align: 'center',
          scopedSlots: {
            customRender: 'oaLshRender',
          },
        },
        {
          title: '违约类型',
          dataIndex: 'qualityType',
          width: '300px',
          align: 'center',
          scopedSlots: {
            customRender: 'qualityTypeRender',
          },
        },
        {
          title: '审批扣罚金额',
          dataIndex: 'spFineAmount',
          width: '120px',
          align: 'center',
        },
        {
          title: '开票金额',
          width: '120px',
          align: 'center',
          scopedSlots: {
            customRender: 'reduceRender',
          },
        },
        {
          title: '本次扣罚',
          width: '120px',
          align: 'center',
          scopedSlots: {
            customRender: 'fineRender',
          },
        },
        {
          title: '状态',
          width: '120px',
          align: 'center',
          scopedSlots: {
            customRender: 'statusRender',
          },
        },
        {
          title: '来源',
          dataIndex: 'platForm',
          width: '70px',
          align: 'center',
        },
        {
          title: '操作',
          width: '70px',
          align: 'center',
          scopedSlots: {
            customRender: 'activeRender',
          },
        },
      ],
      psQualityRecords: [],
      hteQualityRecords: [],
      qualityRecords: [],
      muti: false,
      flow: {},
      process: {
        taskDefKey: '',
      },
      permission: [],
      fineAmountTotal: 0,
      reduceAmountTotal: 0,
      codes: {},
      comments: [],
      showPrintContainer: false,
      showPrintContainer1: false,
      showPaymentFlowTips: false,
      snapshotConfigs: [
        {
          type: 'ref',
          value: 'imageWrapper',
        },
      ],
      showSettlementDetail: false,
      signCompany: [],
      projectBuildVo: {},
      costCenterData: {
        title: '选择成本中心号',
        searchPlaceholder: '请输入关键词进行模糊搜索',
        visible: false,
        url: '/costCenter/list',
        params: {
          companyCode: '',
          costCenterName: '',
        },
        keywordKey: 'costCenterName',
        columns: [
          {
            title: '成本中心号',
            dataIndex: 'costCenter',
            align: 'center',
          },
          {
            title: '成本中心名称',
            dataIndex: 'costCenterName',
            align: 'center',
          },
        ],
      },
      alertMsg: '',
      alertDesc: '',
      alertShow: false,
      currentRoute: this.$route,
      needBeforeSubmit: false,
      yesOrNot: [
        { code: false, name: '否' },
        { code: true, name: '是' },
      ],
      spinning:false,
      spinTip:"检测中，请稍后.....",//正在提交流程引擎,请稍后.....
      submitStart:null,
      timeOuter:null,
      taskCheckShow:false,
      taskCheckBtnShow:false,
      taskCheckResult:{
        checkCostNumberResult:{},
        checkAmountResult:{},
        checkAuditingResult:{}
      },
      taskCheckOkText:'确定',
      showRelateQualityListByPo:false
    }
  },
  computed: {},
  mounted() {
    this.init()
    this.fetchSignCompany()
    this.fetchCodes([
      'WorkReportResultType',
      'WorkReportResultStatus',
      'WorkReportDelayReson',
      'WorkReportNodeStatus',
      'WorkReportDelayRemark',
      'FileCondition',
      'WorkReportQualityStatus',
      '数字贷备案证名称',
      '质量通知单类型',
      '甲方乙方',
      '正常-逾期',
      '是否',
      '减少不变',
      '验收付款表开启检测'
    ])
  },
  methods: {
    formatDate,
    calcDaysBetween,
    init() {
      if (this.taskId != '-1') {
        this.fetchTask(this.taskId)
      }
      if (this.paymentId != '-1') {
        this.fetchPayment()
      }
    },
    fetchSignCompany() {
      getAction(this.urls.loadSignCompany, {}).then((res) => {
        if (res.code == 200) {
          this.signCompany = res.result
        } else {
          this.$messageWorkReport.warning('请求数据失败:' + res.msg)
        }
      })
    },
    fetchPermission() {
      getAction(this.urls.myPermission, {
        projectId: this.task.projectId,
      }).then((res) => {
        if (res.success) {
          this.permission = res.result
        }
      })
    },
    checkPermission(powers) {
      let hasPower = false
      for (let p of powers) {
        if (this.permission.indexOf(p) > -1) {
          hasPower = true
          break
        }
      }
      return hasPower
    },
    async fetchPayment() {
      let res = await getAction(this.urls.payment + '/' + this.paymentId, {})
      if (res.success) {
        this.payment = res.result
        if (!this.payment) {
          this.payment = {}
        } else {
          this.fetchTask(this.payment.taskId)
          this.initQuality()
        }
        if (this.payment.payByLetter != '是') {
          this.$set(this.payment, 'payByLetter', '否')
        }
        if (this.payment.isPrePay != '是') {
          this.$set(this.payment, 'isPrePay', '否')
        }
      }
    },

    fetchTask(taskId) {
      if (!taskId) {
        return
      }
      getAction(this.urls.task + '/' + taskId, {}).then((res) => {
        if (res.success) {
          this.task = res.result
          if (!this.task) {
            this.task = {
              currentHandlerUser: '',
            }
          }
          // 校验必填项
          if (this.task.nodeIdentify != '验收') {
            this.$set(this.rules, 'acceptDept', [])
            this.$set(this.rules, 'acceptUserName', [])
            this.$set(this.rules, 'equipmentAddr', [])
            this.$set(this.rules, 'warrantyYears', [])
            this.$set(this.rules, 'projectAddr', [])
          }
          this.fetchProject()
          this.fetchPermission()
          this.$set(this.payment, 'poLine', this.task.poLine)
          if (!this.payment.postAmount || !this.payment.payAmount) {
            if (this.payment.postAmount != 0 && this.payment.payAmount != 0) {
              this.calcReduce()
            }
          }
          this.taskCheckBtnShow=this.task.isPayNode == '1'&&this.task.poLine&&this.task.poLine!=''&&this.task.paymentAmount!=null;
        }
      })
    },
    fetchProject() {
      getAction(this.urls.project + '/' + this.task.projectId, {}).then((res) => {
        if (res.success) {
          if (res.result && res.result.poLineCount) {
            res.result.poLineCountCopy = '共' + res.result.poLineCount + '行'
          }
          this.project = res.result
          console.log('project info:',this.project)
          if (!this.project.waterAndElectricityPay) {
            this.$set(this.project, 'waterAndElectricityPay', '1')
          }
          this.$set(this.payment, 'contractName', this.project.contractName)
          this.fetchQualityList()
        }
      })
    },
    selectCostCenter() {
      this.$refs.costCenterSelect.open()
    },
    costCenterHandleOk(costCenterData) {
      this.payment.costNumber = costCenterData[0].costCenter
      this.$refs.costCenterSelect.close()
    },
    async handleSave(type=1) {
      console.info('handleSave>20')
      let valid = await this.$refs.ruleForm.validate()
      console.info('handleSave>21')
      if (valid) {
        console.info('handleSave>22')
        this.$set(this.payment, 'taskId', this.task.id)
        this.$set(this.payment, 'paymentQualities', this.qualityRecords)
        let res = await postAction(this.urls.editPayment, this.payment)
        console.info('handleSave>23')
        if (res.success) {
          if(type==1){
            this.$messageWorkReport.success('保存成功')
          }
          this.init()
        } else {
          this.$messageWorkReport.error('保存失败:' + res.msg)
        }
      }
      console.info('handleSave>24')
    },
    async handleSubmit() {
      if (!this.payment.payByLetter) {
        return this.$messageWorkReport.warning('请选择凭保证函付款')
      }
      if (!this.payment.fileCondition) {
        return this.$messageWorkReport.warning('请选择合同资料情况')
      }
      if (!this.payment.proManager) {
        return this.$messageWorkReport.warning('请选择项目经理')
      }
      if (this.task.nodeIdentify == '验收') {
        if (!this.payment.warrantyYears) {
          return this.$messageWorkReport.warning('请输入质保期限')
        }
        if (!this.payment.acceptDept) {
          return this.$messageWorkReport.warning('请输入验收参与部门')
        }
        if (!this.payment.acceptUserName) {
          return this.$messageWorkReport.warning('请输入验收参与人')
        }
        if (!this.payment.projectAddr) {
          return this.$messageWorkReport.warning('请输入项目所在地')
        }
        if (!this.payment.equipmentAddr) {
          return this.$messageWorkReport.warning('请输入设备所在位置')
        }
      }
      if (this.signCompany) {
        let isCorrect = false
        this.signCompany.forEach((c) => {
          if (c.componyNo == this.project.signCompanyCode && c.componyName == this.project.signCompany) {
            isCorrect = true
          }
        })
        if (!isCorrect) {
          return this.$messageWorkReport.warning(
            '当前签订公司[' +
              this.project.signCompany +
              '/' +
              this.project.signCompanyCode +
              ']不正确，请[合同报工管理员]在合同页面进行修正'
          )
        }
      }
      if(this.taskCheckBtnShow){
        this.reportTaskCheck('submit');
      }else{
        this.beforeSubmitCheck('submit')
      }
    },
    async checkDuplicatePayment(action = 'openUserSelector') {
      console.info('checkDuplicatePayment>8')
      console.info('checkDuplicatePayment>action=' + action)
      let res = await getAction(
        this.urls.checkDuplicatePayment + '?taskId=' + this.task.id + '&paymentId=' + this.payment.id
      )
      if (res.success) {
        console.info('checkDuplicatePayment>9')
        let result = res.result
        if ((result.status1 && result.status1 > 0) || (result.status2 && result.status2 > 0)) {
          console.info('checkDuplicatePayment>10')
          return true
        } else {
          return false
        }
      } else {
        this.$messageWorkReport.error('校验是否多次提交分期付款表失败')
        return false
      }
    },
    confirmDuplicatePayment() {
      return new Promise((resolve, reject) => {
        let content = '当前任务已存在其他[审批中]或[审批完成]的验收付款表，是否继续提交审批，请确认'
        let that = this
        Modal.confirm({
          title: '重新发起',
          content: content,
          wrapClassName: 'approvalBox',
          onOk() {
            resolve(true)
          },
          onCancel() {
            resolve(false)
          },
        })
      })
    },
    async openProcessUserSelect() {
      if (this.payment.id != '-1') {
        let res = await getAction(this.urls.flowNode + '?id=' + this.payment.id, {})
        if (res.success) {
          this.$refs.ProcessUserSelect.doSelect(res.result)
          return true
        } else {
          this.$messageWorkReport.warning(res.message)
          return false
        }
      }
    },
    async selectUserConfirm(cols) {
      if (this.process.taskDefKey == 'APPLY_USER_NODE') {
        cols.forEach((c) => {
          if (c.value && c.value != null) {
            this.$set(this.custom, c.node, c.value)
          } else {
            this.$set(this.custom, c.node, '')
          }
        })
        this.$refs.childrenRef.custom = this.custom
        this.$refs.childrenRef.submitTaskNotBefore()
        return true
      }
      this.spinning=true;
      let res = await postAction(this.urls.startFlow + '?id=' + this.payment.id, cols)
      this.spinning=false;
      if (res.success) {
        this.$messageWorkReport.success('提交成功')
        this.init()
        return true
      } else {
        this.$messageWorkReport.error(res.message)
        return false
      }
    },
    async checkProjectBUildDigitalLoan() {
      let projectNo
      if (this.task.costNumber) {
        let costNumber = this.task.costNumber.split(',')[0]
        projectNo = costNumber.split('.')[0]
      }
      let res = await getAction(this.urls.checkProjectBUildDigitalLoan + '?projectNo=' + projectNo)
      if (res.success) {
        this.projectBuildVo = res.result
      }
    },
    toPayment() {
      this.$set(this.payment, 'isSendPay', 1)
    },
    openDeptSelector() {
      this.showDeptSelector = true
    },
    selectDept(selection) {
      let acceptDeptId = this.payment.acceptDeptId
      if (selection && selection.length > 0) {
        this.$set(this.payment, 'acceptDept', selection[0].deptname.trim())
        this.$set(this.payment, 'acceptDeptId', selection[0].deptcode.trim())
        if (acceptDeptId != selection[0].deptcde) {
          this.acceptUserId = ''
          this.acceptUserName = ''
        }
      }
      this.showDeptSelector = false
    },
    toCalcReduce(index, type) {
      let records = [...this.qualityRecords]
      records[index][type] = this.qualityRecords[index][type]
      this.qualityRecords = records
      this.calcReduce()
    },
    calcReduce() {
      let reduceQuality = []
      let reduceTotal = 0
      let fineQuality = []
      let fineTotal = 0
      for (let q of this.qualityRecords) {
        if (q.fine == '1') {
          if (q.reduce == '1') {
            reduceTotal += parseFloat(q.spFineAmount ? q.spFineAmount : 0)
          }
          fineTotal += parseFloat(q.spFineAmount ? q.spFineAmount : 0)
        }
        reduceQuality.push(q.id + '_' + (q.reduce ? q.reduce : ''))
        fineQuality.push(q.id + '_' + (q.fine ? q.fine : ''))
      }
      let payAmount = this.task.paymentAmount - fineTotal
      payAmount = payAmount.toFixed(2)
      let postAmount = this.task.paymentAmount - reduceTotal
      postAmount = postAmount.toFixed(2)
      this.$set(this.payment, 'payAmount', payAmount)
      this.$set(this.payment, 'postAmount', postAmount)

      reduceTotal = reduceTotal.toFixed(2)
      this.$set(this.payment, 'reduceAmount', reduceTotal)
      this.$set(this.payment, 'reduceQuality', reduceQuality.join(','))

      fineTotal = fineTotal.toFixed(2)
      this.$set(this.payment, 'fineAmount', fineTotal)
      this.$set(this.payment, 'fineQuality', fineQuality.join(','))
    },
    selectUser(selection) {
      if (selection && selection.length > 0) {
        if (this.userSelectType == 'accept') {
          let userName = []
          let realName = []
          selection.forEach((user) => {
            userName.push(user.username.trim())
            realName.push(user.realname.trim())
          })
          this.$set(this.payment, 'acceptUserId', userName.join(','))
          this.$set(this.payment, 'acceptUserName', realName.join(','))
        }
        if (this.userSelectType == 'apply') {
          if (selection.length > 0) {
            this.$set(this.payment, 'applyUserId', selection[0].username.trim())
            this.$set(this.payment, 'applyUserName', selection[0].realname.trim())
            this.$set(this.payment, 'applyDeptId', selection[0].deptCode.trim())
            this.$set(this.payment, 'applyDept', selection[0].deptName.trim())
          }
        }
        if (this.userSelectType == 'manager') {
          if (selection.length > 0) {
            this.$set(this.payment, 'proDeptManager', selection[0].realname.trim())
            this.$set(this.payment, 'proDeptManagerId', selection[0].username.trim())
          }
        }
      }
      this.showUserSelector = false
    },
    openUserSelector(type, muti) {
      this.deptCode = '-1'
      this.muti = muti
      this.userSelectType = type
      this.showUserSelector = true
    },
    async fetchQualityList() {
      this.fetchPaymentQualityList()
    },
    async fetchPaymentQualityList() {
      let param = {}
      param.paymentId = this.payment.id
      param.pageSize = 10000
      let res = await postAction(this.urls.paymentQualityList, param)
      if (res.success) {
        this.qualityRecords = res.result
      }
    },
    async fetchPsQualityList() {
      let param = {}
      param.poNo = this.project.busKey
      param.pageSize = 10000
      param.type = 'all'
      let res = await postAction(this.urls.psQualityList, param)
      if (res.success) {
        this.psQualityRecords = res.result.records
        this.psQualityRecords.forEach((r) => {
          r.platForm = '海澜'
        })
        this.qualityRecords = [...this.psQualityRecords, ...this.hteQualityRecords]
      }
    },
    async fetchHteQualityList() {
      let param = {}
      param.poNo = this.project.busKey
      param.type = 'all'
      let res = await postAction(this.urls.hteQualityList, param)
      if (res.success) {
        this.hteQualityRecords = res.result //.records
        this.hteQualityRecords.forEach((r) => {
          r.platForm = '海芯'
        })
        // this.$set(this.qualityIpagination, 'total', res.result.total)
        this.qualityRecords = [...this.psQualityRecords, ...this.hteQualityRecords]
      }
    },
    initQuality() {
      let filterQuality = []
      if (
        this.payment &&
        (!this.payment.status || this.payment.status == '0' || this.payment.status == '1' || this.payment.status == '3')
      ) {
        filterQuality = this.qualityRecords
      } else if (this.payment && this.payment.status == '2') {
        if (this.payment.fineQuality) {
          let fineQuality = ',' + this.payment.fineQuality
          for (let q of this.qualityRecords) {
            let key = q.id + '_'
            if (fineQuality.indexOf(key) > -1) {
              filterQuality.push(q)
            }
          }
        }
      }
      this.qualityRecords = filterQuality
      let stayStatus4 = []
      if (this.qualityRecords && this.payment && this.payment.reduceQuality) {
        let reduceQuality = this.payment.reduceQuality.split(',')
        this.qualityRecords.forEach((r) => {
          if (this.payment.fineQuality.indexOf('_') <= -1) {
            if (reduceQuality.indexOf(r.id + '') > -1) {
              stayStatus4.push(r.id)
              r.reduce = '1'
            } else {
              r.reduce = '0'
            }
          } else {
            if (reduceQuality.indexOf(r.id + '_1') > -1) {
              stayStatus4.push(r.id)
              r.reduce = '1'
            }
            if (reduceQuality.indexOf(r.id + '_0') > -1) {
              stayStatus4.push(r.id)
              r.reduce = '0'
            }
            if (reduceQuality.indexOf(r.id + '_') > -1) {
              stayStatus4.push(r.id)
              r.reduce = ''
            }
          }
        })
      }
      if (this.qualityRecords && this.payment && this.payment.fineQuality) {
        let findQuality = this.payment.fineQuality.split(',')
        this.qualityRecords.forEach((r) => {
          if (this.payment.fineQuality.indexOf('_') <= -1) {
            if (findQuality.indexOf(r.id + '') > -1) {
              stayStatus4.push(r.id)
              r.fine = '1'
            } else {
              r.fine = '0'
            }
          } else {
            if (findQuality.indexOf(r.id + '_1') > -1) {
              stayStatus4.push(r.id)
              r.fine = '1'
            }
            if (findQuality.indexOf(r.id + '_0') > -1) {
              stayStatus4.push(r.id)
              r.fine = '0'
            }
            if (findQuality.indexOf(r.id + '_') > -1) {
              stayStatus4.push(r.id)
              r.fine = ''
            }
          }
        })
      }
      let finalyRecords = []
      this.qualityRecords.forEach((q) => {
        if (q.status != '4') {
          finalyRecords.push(q)
        } else {
          if (stayStatus4.indexOf(q.id) > -1) {
            finalyRecords.push(q)
          }
        }
      })
      this.qualityRecords = finalyRecords
    },

    handleTableChange(pagination, filters, sorter) {
      this.qualityQuery = pagination
      this.qualityQuery.pageNo = this.qualityQuery.current
      this.fetchQualityList()
    },

    toQuality(record) {
      if (record.platForm == '海澜') {
        let urlJump = this.$router.resolve({ path: '/workReport/quality/view/' + record.qualityId + '/' + this.taskId })
        window.open(urlJump.href, '_blank')
      } else {
        let urlJump = this.$router.resolve({ path: '/workReport/editQuality/' + record.qualityId })
        window.open(urlJump.href, '_blank')
      }
    },
    toTaskDetail() {
      let urlJump = this.$router.resolve({ path: '/workReport/taskDetail/' + this.task.id })
      window.open(urlJump.href, '_blank')
    },
    toContractAttach() {
      let urlJump = this.$router.resolve({ path: '/workReport/attach/' + this.project.id })
      window.open(urlJump.href, '_blank')
    },
    changeWarrantyYears() {
      let applyTime = this.payment.applyTime
      if (!applyTime) {
        applyTime = new Date()
      } else {
        applyTime = new Date(applyTime)
      }
      let warrantyYears = this.payment.warrantyYears
      if (warrantyYears) {
        warrantyYears = applyTime.getMonth() + 1 + parseInt(warrantyYears)
        applyTime.setYear(applyTime.getFullYear() + parseInt(parseInt(warrantyYears) / 12))
        let month = parseInt(parseInt(warrantyYears) % 12)
        let years = applyTime.getFullYear()
        if (month == 0) {
          month = 12
          years = years - 1
        }
        this.$set(this.payment, 'warrantyTime', years + '-' + month + '-' + applyTime.getDate())
      }
    },
    async print() {
      await this.fetchFlowComments(this.payment.processInstanceId)
      await this.fetchFlowNotifys(this.payment.processInstanceId)
      setTimeout(this.$refs.printPayment.print(), 2000)
    },
    async print1() {
      await this.fetchFlowComments(this.payment.processInstanceId)
      setTimeout(this.$refs.printAccept.print(), 2000)
    },
    printSnap() {
      this.$printer(this.$refs.printSnapContainer)
    },
    async updateStatus() {
      await getActionAsync(this.approvalActions.passUrl + '/' + this.paymentId, {}).then((res) => {
        if (res.code == 200) {
          this.$messageWorkReport.success('更新成功')
        } else {
          this.$messageWorkReport.warning('流程审批通过接口异常:' + res.message)
        }
      })
    },
    reportTaskCheck(submit){
      if(this.codes['验收付款表开启检测']&& this.codes['验收付款表开启检测'][0] && this.codes['验收付款表开启检测'][0].code=='0'){
        if(submit&&submit=='submit'){
            this.beforeSubmitCheck('submit');
          }else if(submit&&submit=='audit'){
            this.handleSubmitTask();
          }
        return
      }
      let taskId=this.taskId?this.taskId:this.payment.taskId;
      this.spinning=true;
      this.spinTip="检测中，请稍后.....";
      getAction(this.urls.taskCheck + '/' + taskId, {}).then((res) => {
        this.spinning=false;
        if (res.success) {
          this.taskCheckResult = res.result||{};
          if(submit&&submit=='submit'){
            this.taskCheckOkText="确定提交";
          }else if(submit&&submit=='audit'){
            this.taskCheckOkText="同意流转";
          }else{
            this.taskCheckOkText="确定";
          }
          if(submit&&submit=='audit'&&this.taskCheckResult.checkCostNumberResult.checkResult==='1'
            &&this.taskCheckResult.checkAmountResult.checkResult==='1'
            &&this.taskCheckResult.checkAuditingResult.checkResult==='1'){
            this.handleSubmitTask();
          }else{
            this.taskCheckShow=true;
          }
        }else{
          this.$messageWorkReport.warning('异常检测失败：'+res.message)
        }
      }).catch(error => {
        this.spinning=false;
        this.$messageWorkReport.warning('异常检测失败：'+error.message)
      })
    },
    taskCheckOk(){
      const vm=this;
      if(this.taskCheckOkText==="确定提交"){
        if(this.taskCheckResult.checkCostNumberResult.checkResult==='0'
          ||this.taskCheckResult.checkAmountResult.checkResult==='0'
          ||this.taskCheckResult.checkAuditingResult.checkResult==='0'){
          Modal.confirm({
            content:'检测存在异常情况，确定提交流程吗？',
            title: '异常检测确认',
            onOk: () => {
              vm.taskCheckShow=false;
              vm.spinTip="正在提交流程引擎,请稍后.....";
              vm.beforeSubmitCheck('submit');
            },
            onCancel() {
            },
          })
          return;
        }
        this.taskCheckShow=false;
        this.spinTip="正在提交流程引擎,请稍后.....";
        this.beforeSubmitCheck('submit');
      }else if(this.taskCheckOkText==="同意流转"){
        Modal.confirm({
          content:'检测存在异常情况，确定继续流转流程吗？',
          title: '异常检测确认',
          onOk: () => {
            vm.taskCheckShow=false;
            vm.handleSubmitTask();
          },
          onCancel() {
          },
        })
        return;
      }
      this.taskCheckShow=false;
    },
    beforeSubmit(res) {
      console.info(res)
      this.$set(this.custom, 'digitalLoan', this.payment.digitalLoan)
      this.$refs.childrenRef.custom = this.custom
      if (this.process.taskDefKey == 'userDept' && !this.payment.costNumber) {
        this.$messageWorkReport.warning('请选择部门成本中心号')
        return false
      }
      this.beforeSubmitCheck()
      return false
    },
    async beforeSubmitCheck(type) {
      if (this.process.taskDefKey == 'POST_DEPT_NODE' && this.payment.hasPost != 2) {
        //执行一次自动过账
        await this.handleReAutoPost()
       
        if(this.payment.hasPost != 2){
          return this.$message.warning("尝试过账失败，请联系IT")
        }
      }
      let digitalLoanCheck = false
      await this.checkDigitalLoan().then((res) => {
        digitalLoanCheck = res
      })
      console.info('digitalLoanCheck=' + digitalLoanCheck)
      if (!digitalLoanCheck) {
        return
      }
      await this.handleSave(0)
      let duplicateCheck = await this.checkDuplicatePayment()
      console.info('duplicateCheck=' + duplicateCheck)
      if (duplicateCheck) {
        let comfirmDuplicate = true
        await this.confirmDuplicatePayment().then((res) => {
          comfirmDuplicate = res
        })
        console.info('comfirmDuplicate=' + comfirmDuplicate)
        if (!comfirmDuplicate) {
          return
        }
      }
      if (type == 'submit' || ['APPLY_USER_NODE'].indexOf(this.process.taskDefKey) > -1) {
        this.openProcessUserSelect()
      } else {
        this.spinning = true
        if (this.timeOuter) {
        window.clearTimeout(this.timeOuter)
        }
        if(this.process.taskDefKey != 'userDept' && this.process.taskDefKey != 'keepDept'){
          this.reportTaskCheck('audit')
        }else{
          this.handleSubmitTask();
        }
      }
    },
    handleSubmitTask(){
      this.timeOuter = window.setTimeout(this.closeSpinning, 5000)
      let msg = '验收付款表[' + this.payment.applyNo + ']同意操作已完成'
      this.alertMsg = '流程正在审批中,请稍等...'
      this.alertShow = true
      console.info("提交审批开始")
      this.submitStart = new Date()
      this.$refs.childrenRef.submitTaskNotBefore()
    },
    closeSpinning(){
      if(this.spinning){
        // this.$message.warning("流程引擎5秒内未返回执行结果,自动关闭遮罩层")
        this.spinning = false
      }
    },
    checkDigitalLoan() {
      return new Promise((resolve, reject) => {
        let result = true
        if (
          ['PRO_DEPT_MANAGER_NODE', 'PRO_MANAGER_NODE', 'FOLLOW_USER_NODE', 'PURCHASE_DEPT_USER'].indexOf(
            this.process.taskDefKey
          ) > -1
        ) {
          console.info('beforeSubmitCheck->4')
          if (!this.projectBuildVo) {
            this.projectBuildVo = {}
          }
          if (!this.payment.digitalLoan) {
            this.payment.digitalLoan = false
          }
          if (!this.projectBuildVo.digitalLoan) {
            this.projectBuildVo.digitalLoan = false
          }
          if (!this.payment.filingName) {
            this.payment.filingName = ''
          }
          if (!this.projectBuildVo.filingName) {
            this.projectBuildVo.filingName = ''
          }
          if (
            !(
              this.projectBuildVo &&
              this.projectBuildVo.digitalLoan == this.payment.digitalLoan &&
              this.projectBuildVo.filingName == this.payment.filingName
            )
          ) {
            let that = this
            Modal.confirm({
              content:
                '验收付款表是否数字贷信息与海芯立项项目不一致，是否需要修改，无需修改请选择【继续提交】，需要修改请选择【返回修改】，修改后重新提交',
              title: '数字贷信息不一致提醒',
              cancelText: '返回修改',
              okText: '继续提交',
              onOk: () => {
                resolve(true)
              },
              onCancel() {
                reject(false)
              },
            })
          } else {
            resolve(true)
          }
        } else {
          resolve(true)
        }
      })
    },
    reSelectUser(flow) {
      let that = this
      postAction(this.urls.getProcessMap, flow).then((res) => {
        if (res.success) {
          that.$set(that.custom, 'applyUser', res.result.applyUser)
          that.$set(that.custom, 'proDeptManager', res.result.proDeptManager)
          that.$set(that.custom, 'proManager', res.result.proManager)
          that.$set(that.custom, 'followUser', res.result.followUser)
          that.$set(that.custom, 'userDeptUser', res.result.userDeptUser)
          that.$set(that.custom, 'keepDeptUser', res.result.keepDeptUser)
          that.$set(that.custom, 'costDeptUser', res.result.costDeptUser)
          that.$set(that.custom, 'budgetUser', res.result.budgetUser)
          that.$set(that.custom, 'budgetDeptHead', res.result.budgetDeptHead)
          that.$set(that.custom, 'purchaseDeptUser', res.result.purchaseDeptUser)
          that.$set(that.custom, 'contractSignManager', res.result.contractSignManager)
          that.$set(that.custom, 'deptHeader', res.result.deptHeader)
          that.$set(that.custom, 'postUser', res.result.postUser)
          that.$set(that.custom, 'settlementUser', res.result.settlementUser)
          that.$set(that.custom, 'flowType', res.result.flowType)
          that.$set(that.custom, 'isNeedCostDept', res.result.isNeedCostDept)
          that.$set(that.custom, 'isNeedDeptHeader', res.result.isNeedDeptHeader)
          that.$set(that.custom, 'isNeedPro', res.result.isNeedPro)
          that.$set(that.custom, 'followUserCanEnd', res.result.followUserCanEnd)
          that.$refs.childrenRef.custom = that.custom
          that.$refs.childrenRef.submitTaskNotBefore()
        } else {
          that.$messageWorkReport.error(res.message)
        }
      })
    },
    afterSubmit(res) {
      this.spinning = false
      let that = this
      let msg = '验收付款表[' + this.payment.applyNo + ']同意操作已完成'
      this.alertMsg = '流程提交审批已完成'
      this.alertShow = true
      console.info("提交审批耗时:"+(new Date().getTime()-this.submitStart.getTime())/1000.0+"秒")
      console.info("提交审批完成")
      that.closeSelectedTag(that.currentRoute, this.payment.processInstanceId, msg)
      return true
    },
    openSettlementDetail() {
      this.showSettlementDetail = true
    },
    closeSettlementDetail() {
      this.showSettlementDetail = false
    },
    toQualityListByPo() {
      if (this.project.busKey) {
        let urlJump = this.$router.resolve({ path: '/workReport/qualityList/' + this.project.busKey })
        window.open(urlJump.href, '_blank')
      }
    },
    toTaskList() {
      if (this.project.id) {
        let urlJump = this.$router.resolve({ path: '/workReport/taskList?projectId=' + this.project.id })
        window.open(urlJump.href, '_blank')
      }
    },

   async handleReAutoPost() {
      let res = await getAction(this.urls.reAutoPost + '?paymentId=' + this.paymentId)
        if (res.code == 200) {
          this.$messageWorkReport.success('过账成功')
          let res = await getAction(this.urls.payment + '/' + this.paymentId, {})
        if (res.success) {
          let payment = res.result
          this.$set(this.payment,"postTime",payment.postTime)
          this.$set(this.payment,"postNo",payment.postNo)
          this.$set(this.payment,"hasPost",payment.hasPost)
          this.$set(this.payment,"postMsg",payment.postMsg)
          this.$set(this.payment,"postParams",payment.postParams)
          this.$set(this.payment,"postYear",payment.postYear)
        }
        } else {
          this.$messageWorkReport.error(res.message)
        }
    },
    changeDiaitalLoan() {
      if (this.payment.digitalLoan) {
        this.$set(this.payment, 'filingName', '')
      }
    },
    reloadQualityList() {
      getAction(this.urls.reloadQualityList + '?paymentId=' + this.paymentId).then(async (res) => {
        if (res.code == 200) {
          this.fetchPaymentQualityList()
          this.$messageWorkReport.success('重新加载质量通知单成功')
        } else {
          this.$messageWorkReport.error('重新加载质量通知单失败')
        }
      })
    },
    removePaymentQuality(record) {
      let that = this
      Modal.confirm({
        title: '移除提醒',
        content: '请确认是否移除当前质量通知单',
        onOk() {
          postAction(that.urls.removePaymentQuality + '/' + record.id).then(async (res) => {
            if (res.code == 200) {
              that.fetchPaymentQualityList()
              that.$messageWorkReport.success('删除成功')
            } else {
              that.$messageWorkReport.error('删除失败')
            }
          })
        },
        onCancel() {},
      })
    },
    openTaskPop(){
      this.$refs.TaskPop.open(this.project.id)
    },
    //相关质量通知单
    relateQualityListByPo(){
        console.log('相关质量通知单')
        this.showRelateQualityListByPo = true
    },
    async closeRelateQuanlityListByPo(data){
      console.log(data)
      this.showRelateQualityListByPo = false
      if(data && data.length > 0){
          console.log('select data:',JSON.stringify(data))
          //this.task.paymentId
          //this.paymentId
          //this.urls.relateQualityToTaskPayment
          console.log('this.task.paymentId:',this.task.paymentId)
          console.log('this.paymentId:',this.paymentId)
          let resParam = {taskPaymentId:this.paymentId,qualityNo:data}
          console.log('resParam',resParam)
          postAction(this.urls.relateQualityToTaskPayment,resParam).then(res=>{
            if(res.code == 200){
              this.$messageWorkReport.success('关联成功')
            }else{
              this.$messageWorkReport.success('关联失败')
            }
          })
      }
     
    },

  },
  watch: {
    taskId: {
      handler(newV, oldV) {
        if (newV != '-1') {
          this.fetchTask()
        }
      },
      deep: true,
      immediate: true,
    },
    paymentId: {
      handler(newV, oldV) {
        if (newV != '-1') {
          this.fetchPayment()
        }
      },
      deep: true,
      immediate: true,
    },
    'task.costNumber': {
      handler(newV, oldV) {
        this.checkProjectBUildDigitalLoan()
      },
      deep: true,
      immediate: true,
    },
    'task.complateTime': {
      handler(newV, oldV) {
        let endTime = new Date()
        if (this.task.partaStatus == '2') {
          endTime = this.task.partaActualTime ? this.task.partaActualTime + ' 23:59:59.999' : ''
        }
        let temp = this.calcDaysBetween(this.task.complateTime + ' 23:59:59.999', endTime)
        this.$set(this.task, 'partaNodeStatus', temp.status)
        if (temp.status != '正常') {
          this.$set(this.task, 'partaDelayDays', temp.days)
        } else {
          this.$set(this.task, 'partaDelayDays', 0)
          this.$set(this.task, 'partaDelayReason', '')
        }
      },
      deep: true,
      immediate: true,
    },
    'task.partaActualTime': {
      handler(newV, oldV) {
        let endTime = new Date()
        if (this.task.partaStatus == '2') {
          endTime = this.task.partaActualTime ? this.task.partaActualTime + ' 23:59:59.999' : ''
        }
        let temp = this.calcDaysBetween(this.task.complateTime + ' 23:59:59.999', endTime)
        this.$set(this.task, 'partaNodeStatus', temp.status)
        if (temp.status != '正常') {
          this.$set(this.task, 'partaDelayDays', temp.days)
        } else {
          this.$set(this.task, 'partaDelayDays', 0)
          this.$set(this.task, 'partaDelayReason', '')
        }
      },
      deep: true,
      immediate: true,
    },
    'payment.processInstanceId': {
      handler(newV, oldV) {
        if (this.payment.processInstanceId) {
          this.fetchProcess(this.payment.processInstanceId)
          this.fetchFlowComments(this.payment.processInstanceId)
        }
      },
      deep: true,
      immediate: true,
    },
  },
}
</script>

<style lang="less" scoped>
@import '~@assets/less/hte-main.less';

.page-main {
  .container {
    /deep/ .ant-alert-success {
      text-align: center;
    }

    /deep/ .ant-alert-message {
      font-size: 20px;
      font-weight: bold;
      color: red;
    }

    .content {
      margin-top: 20px;

      section {
        padding: 32px 29px 20px;
        background: #fff;
        margin-bottom: 18px;
        border: solid 1px #e2e2e2;

        .section-header {
          font-size: 16px;
          font-weight: bold;
          position: relative;
          padding-left: 14px;
          color: #333333;
          margin-bottom: 14px;

          &:before {
            &:extend(.afterbg);
            width: 3px;
            left: 0;
            background-color: #47a4fa;
            border-radius: 1px;
          }
        }

        .col-input-2 {
          /deep/ .ant-select,
          /deep/ input {
            width: 49%;

            &:first-child {
              margin-right: 2%;
            }
          }

          &.col-input-font /deep/ .ant-select-selection-selected-value,
          &.col-input-font /deep/ .ant-input {
            color: #de2626 !important;
          }
        }

        .section-table {
          .mr10 {
            margin-right: 10px;
          }

          .btn-box {
            margin-bottom: 15px;

            .hte-btn:first-child {
              margin-left: 0;
            }
          }

          .add-btn {
            margin-left: 0;
            margin-bottom: 10px;
          }

          /deep/ .el-upload__input {
            display: none !important;
          }
        }

        .line-section {
          padding: 15px 0;
          margin-top: 40px;
          border-top: 1px solid #f2f2f2;
          color: #333;
          display: flex;
          justify-content: space-between;

          span {
            padding-right: 25px;

            &:first-child {
              font-weight: bold;
              font-size: 15px;
            }

            i {
              color: red;
            }
          }

          div > i {
            color: @font-color-active;
          }
        }
      }
    }
  }

  .tips-box {
    margin-top: 32px;

    .add-btn {
      width: 180px;
      height: 40px;
      line-height: 40px;
      background-color: #4095e4;
      border-radius: 2px;
    }
  }
  /deep/ .el-loading-parent--relative .el-loading-mask {
    z-index: 1 !important;
    display: none !important;
  }
}
</style>
<style>
.el-loading-parent--relative .el-loading-mask {
  z-index: 1 !important;
  display: none !important;
}
</style>
<style scoped>
.el-checkbox__label {
  padding-left: 0px !important;
  padding-right: 10px !important;
}
.el-loading-parent--relative .el-loading-mask {
  z-index: 1 !important;
  display: none !important;
}
.el-checkbox >>> .el-checkbox__input.is-disabled .el-checkbox__inner {
  background-color: white !important;
  border-color: black !important;
  cursor: not-allowed;
}

.el-checkbox >>> .el-checkbox__input.is-disabled + span.el-checkbox__label {
  color: black !important;
  cursor: not-allowed;
}

.el-checkbox >>> .el-checkbox__input.is-disabled.is-checked .el-checkbox__inner::after {
  border-color: black !important;
}

.el-form-item >>> .el-form-item__error {
  color: #ff4949;
  font-size: 12px;
  line-height: 1;
  padding-top: 4px;
  position: relative;
  top: 100%;
  left: 0;
}
</style>
<style lang="less" scoped>
/deep/ #process-container {
  width: unset !important;
}

#process-container {
  background: #fff;
  padding: 40px 22px;
  width: auto;
  margin: 0 auto;
  -webkit-box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.15);
  box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.15);
}

.top-200 {
  top: 65px;
  right: 384px;
  border: 1px solid red; //演示加的，用的时候删掉就好
}
</style>
